package com.kumi.shop.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.kumi.shop.product.service.CategoryBrandRelationService;
import com.kumi.shop.product.vo.Catelog2Vo;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kumi.common.utils.PageUtils;
import com.kumi.common.utils.Query;

import com.kumi.shop.product.mapper.CategoryMapper;
import com.kumi.shop.product.bean.Category;
import com.kumi.shop.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<Category> page = this.page(
                new Query<Category>().getPage(params),
                new QueryWrapper<Category>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<Category> listTree() {
        //1.查出所有的数据

        List<Category> categories = baseMapper.selectList(null);
        //2.组装树形结构

        //2.1.找到所有的一级分类
//        List<Category> level1 = categories.stream().filter((category) -> {
//            System.out.println(category); return category.getParentCid() == 0;})
//                .map((category)->{category.setChildren(getChildren(category,categories));return category;})
//                .sorted((category,category2)->(category.getSort()==null?0:category.getSort()) - (category2.getSort()==null?0:category2.getSort()))
//                .collect(Collectors.toList());
//
//
//        return level1;

        List<Category> root = new ArrayList<>();
        Map<Long, Category> menuMap = new HashMap<>();

        for (Category menu : categories) {
            Long id = menu.getCatId();
            menuMap.put(id, menu);

        }

        for (Category menu : categories) {
            long pid = menu.getParentCid();

            if (pid == 0) {
                root.add(menu);

                continue;
            }
            Category father = menuMap.get(pid);
            father.getChildren().add(menu);

        }

        return root;


    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODD//1.检查当前的菜单是否被引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCateLogPath(Long attrlogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> path = findPath(attrlogId, paths);

        Collections.reverse(path);
        return (Long[]) paths.toArray(new Long[path.size()]);
    }

    @Caching(evict = {
            @CacheEvict(value = "category",key = "'catalogJson'"),
            @CacheEvict(value = "category",key = "'getCatalogJson'")
    })
    @Transactional
    @Override
    public void updateData(Category category) {
        this.updateById(category);
        categoryBrandRelationService.updateCate(category.getCatId(), category.getName());
    }



    @Cacheable(value = {"category"},key = "'catalogJson'",sync = true)
    @Override
    public List<Category> getLevel1Category() {
        List<Category> list = baseMapper.selectList(new QueryWrapper<Category>().eq("parent_cid", 0));
        return list;
    }

    @Cacheable(value = {"category"},key = "'getCatalogJson'")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        List<Category> categories = baseMapper.selectList(new QueryWrapper<Category>(null));
        List<Category> level1Category = getLevel1Category();
        Map<String, List<Catelog2Vo>> parent_cid = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<Category> parentCid = getParent_cid(categories, v.getCatId());
            List<Catelog2Vo> collect = null;
            if (parentCid != null) {
                collect = parentCid.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<Category> parentId = getParent_cid(categories, l2.getCatId());
                    if (parentId != null) {
                        List<Catelog2Vo.Catelog3Vo> collect1 = parentId.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect1);

                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        return parent_cid;
    }

        //TODO 产生堆外内存溢出

    public Map<String, List<Catelog2Vo>> getCatalogJson2() {

        Map<String, List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonFromReidssonWithLock();
        return catalogJsonFromDB;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromReidssonWithLock() {

        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> listMap = null;
        try {
            listMap = getListMap();
        } finally {
            lock.unlock();
        }
        return listMap;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromReidsWithLock() {

        String token = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", token, 300, TimeUnit.SECONDS);
        Map<String, List<Catelog2Vo>> listMap = null;
        if (lock) {
            try {
                listMap = getListMap();
            } finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock", token));

            }
            return listMap;
        } else {
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromReidsWithLock();
        }

    }

    private Map<String, List<Catelog2Vo>> getListMap() {
        List<Category> categories = baseMapper.selectList(new QueryWrapper<Category>(null));
        List<Category> level1Category = getLevel1Category();
        Map<String, List<Catelog2Vo>> parent_cid = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<Category> parentCid = getParent_cid(categories, v.getCatId());
            List<Catelog2Vo> collect = null;
            if (parentCid != null) {
                collect = parentCid.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<Category> parentId = getParent_cid(categories, l2.getCatId());
                    if (parentId != null) {
                        List<Catelog2Vo.Catelog3Vo> collect1 = parentId.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect1);

                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithLock() {

        synchronized (this) {
            String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
            if (!StringUtils.isEmpty(catalogJSON)) {
                Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
                return result;
            }
            List<Category> categories = baseMapper.selectList(new QueryWrapper<Category>(null));
            List<Category> level1Category = getLevel1Category();
            Map<String, List<Catelog2Vo>> parent_cid = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                List<Category> parentCid = getParent_cid(categories, v.getCatId());
                List<Catelog2Vo> collect = null;
                if (parentCid != null) {
                    collect = parentCid.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                        List<Category> parentId = getParent_cid(categories, l2.getCatId());
                        if (parentId != null) {
                            List<Catelog2Vo.Catelog3Vo> collect1 = parentId.stream().map(l3 -> {
                                Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                return catelog3Vo;
                            }).collect(Collectors.toList());
                            catelog2Vo.setCatalog3List(collect1);

                        }
                        return catelog2Vo;
                    }).collect(Collectors.toList());
                }

                return collect;
            }));
            String s = JSON.toJSONString(parent_cid);
            redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);

            return parent_cid;
        }
    }

    private List<Category> getParent_cid(List<Category> categories, Long parent_cid) {
//        return baseMapper.selectList(new QueryWrapper<Category>().eq("parent_cid", l2.getCatId()));
        List<Category> collect = categories.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findPath(Long attrlogId, List<Long> paths) {
        Category byId = this.getById(attrlogId);
        paths.add(attrlogId);
        if (byId.getParentCid() != 0) {
            findPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    private List<Category> getChildren(Category root, List<Category> all) {
        List<Category> chilren = all.stream().filter(category -> category.getParentCid() == root.getCatId())
                .map(category -> {
                    category.setChildren(getChildren(category, all));
                    return category;
                })
                .sorted(((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort())))
                .collect(Collectors.toList());
        return chilren;
    }

}